package com.ruoyi.websocket;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.websocket.WebsocketConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 此注解相当于设置访问URL
 */
@Component
@Slf4j
@ServerEndpoint("/websocket/{cabinetNum}") //此注解相当于设置访问URL
public class WebSocketServer {

    private Session session;

    private String cabinetNum;

    private static CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<>();
    private static Map<String, Session> sessionPool = new HashMap<String, Session>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "cabinetNum") String cabinetNum) {
        try {
            this.session = session;
            this.cabinetNum = cabinetNum;
            webSockets.add(this);
            sessionPool.put(cabinetNum, session);
            log.info("【websocket消息】有新的连接，客户端："+cabinetNum+"连接，总数为:" + webSockets.size());
        } catch (Exception e) {
        }
    }

    @OnClose
    public void onClose() {
        try {
            webSockets.remove(this);
            sessionPool.remove(this.cabinetNum);
            log.info("【websocket消息】客户端: "+this.cabinetNum+"连接断开，总数为:" + webSockets.size());
        } catch (Exception e) {
        }
    }


    /**
     * 服务端推送消息
     *
     * @param cabinetNum
     * @param message
     */
    public void pushMessage(String cabinetNum, String message) {
        log.info("websocket发送消息。。{}",message);
        List<String> cabinetNums = StrUtil.split(cabinetNum, ",");
        for (String id : cabinetNums) {
            Session session = sessionPool.get(id);
            if (session != null && session.isOpen()) {
                log.info("【websocket消息】 单点消息:" + message);
                synchronized (session) {
                    session.getAsyncRemote().sendText(message);
                }
            }
        }

    }

    /**
     * 服务器端推送消息
     */
    public void pushMessage(String message) {
        try {
            webSockets.forEach(ws -> ws.session.getAsyncRemote().sendText(message));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @OnMessage
    public void onMessage(String message) {
        log.debug("【websocket消息】收到客户端消息:" + message);
        JSONObject obj = new JSONObject();
        //业务类型
        obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_CHECK);
        //消息内容
        obj.put(WebsocketConst.MSG_TXT, "心跳响应");
        this.pushMessage(message);
    }
}